import { defineStore } from 'pinia'
import { ref } from 'vue'
import { request } from '@/utils/request'

export interface User {
  id: number
  username: string
  realName: string
  role: 'USER' | 'ADMIN'
  email?: string
  phone?: string
}

export interface LoginCredentials {
  username: string
  password: string
}

export interface RegisterData {
  username: string
  password: string
  realName: string
  phone?: string | null
  email?: string | null
}

export const useAuthStore = defineStore('auth', () => {
  const user = ref<User | null>(null)
  const isLoggedIn = ref(false)
  const loading = ref(false)

  const login = async (credentials: LoginCredentials) => {
    loading.value = true
    try {
      const data = await request.post('/users/login', credentials)
      user.value = data
      isLoggedIn.value = true
      localStorage.setItem('user', JSON.stringify(data))
      return data
    } catch (error) {
      console.error('登录失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  const register = async (registerData: RegisterData) => {
    loading.value = true
    try {
      const data = await request.post('/users/register', registerData)
      return data
    } catch (error: any) {
      console.error('注册失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  const logout = async () => {
    try {
      await request.post('/users/logout')
    } catch (error) {
      console.error('登出请求失败:', error)
    } finally {
      user.value = null
      isLoggedIn.value = false
      localStorage.removeItem('user')
    }
  }

  const getCurrentUser = async () => {
    try {
      const data = await request.get('/users/current')
      user.value = data
      isLoggedIn.value = true
      return data
    } catch (error) {
      user.value = null
      isLoggedIn.value = false
      localStorage.removeItem('user')
      throw error
    }
  }

  const initAuth = async () => {
    const savedUser = localStorage.getItem('user')
    if (savedUser) {
      try {
        const userData = JSON.parse(savedUser)
        user.value = userData
        isLoggedIn.value = true
        
        try {
          await getCurrentUser()
        } catch {
          user.value = null
          isLoggedIn.value = false
          localStorage.removeItem('user')
        }
      } catch {
        localStorage.removeItem('user')
      }
    }
  }

  const isAdmin = () => {
    return user.value?.role === 'ADMIN'
  }

  const isUser = () => {
    return user.value?.role === 'USER'
  }

  return {
    user,
    isLoggedIn,
    loading,
    login,
    register,
    logout,
    getCurrentUser,
    initAuth,
    isAdmin,
    isUser
  }
})